import axios from "axios";
import {HOST_URL} from "@/config";
import {ElMessage} from "element-plus";

axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

function unAuth(res) {
    console.log(res)
    if (res.status === 401) {
        localStorage.token = "";
        window.location.replace("/");
    }
}

export default function request(url, type = "GET", data = {}, noAuth = false) {
    return new Promise((resolve, reject) => {
        axios.defaults.baseURL = HOST_URL;
        axios.defaults.timeout = 20000;
        let option = {url, method: type};
        option[type.toLowerCase() === "get" || type.toLowerCase() === "delete" ? "params" : "data"] =
            data;
        option.headers = {};
        option.headers["content-type"] = "application/x-www-form-urlencoded";
        if (localStorage.token && !noAuth) {
            axios.defaults.headers["token"] = localStorage.token;
        }
        axios(option)
            .then((res) => {
                console.log({
                    入参: data,
                    回参: res.data,
                    地址: url,
                    请求: type,
                });
                resolve(res.data);
            })
            .catch((res) => {
                unAuth(res.response);
                reject({msg: "网络异常"});
            });
    });
}
